/* eslint-disable no-use-before-define */
/* eslint-disable react/react-in-jsx-scope */
import useInitialState from '@/hooks/useInitState'
import { getUserProfile, updateUserPhoto, updateUserProfile } from '@/store/actions/profile'

// import { RootState } from '@/types/store'
import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'
import React, { useRef, useState } from 'react'
import EditInput from './EditInput'
import { useHistory } from 'react-router-dom'
// import { useEffect } from 'react'
// import { useDispatch, useSelector } from 'react-redux'

import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import EditList from './EditList'
import { formatDay } from '@/utils/formatDay'
import { logout } from '@/store/actions/login'

const Item = List.Item
type InputType = {
  visible:boolean,
  type:'' | 'name' | 'intro'
}
type ListType = {
  visible:boolean,
  type:'' | 'gender' | 'photo'
}
const ProfileEdit = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const fileRef = useRef<HTMLInputElement>(null)
  // const { user: userProfile } = useSelector((state:RootState) => state.profile)
  // useEffect(() => {
  //   dispatch(getUserProfile())
  // }, [dispatch])
  const [showInput, setShowInput] = useState<InputType>({
    type: '',
    visible: false
  })
  const [showList, setShowList] = useState<ListType>({
    type: '',
    visible: false

  })
  const [showBirthday, setShowBirthday] = useState(false)
  const onBirthdayShow = () => {
    setShowBirthday(true)
  }
  const onBirthdayHide = () => {
    setShowBirthday(false)
  }
  const onUpdateBirthday = async (e:Date) => {
    console.log(e)
    // 用户的生日 e
    // 调用修改个人信息函数
    await onUpdate('birthday', formatDay(e))
    setShowBirthday(false)
  }
  // 关闭弹层
  const hideInput = () => {
    setShowInput({
      type: '',
      visible: false
    })
  }
  // 关闭遮罩层
  const hideList = () => {
    setShowList({
      type: '',
      visible: false
    })
  }
  const onUpdate = async (type:string, value:string) => {
    console.log(type, value)
    if (type === 'photo') {
      fileRef.current!.click()
      return
    }
    // 调用修改个人信息函数
    await dispatch(updateUserProfile(type, value))
    Toast.show({
      icon: 'success',
      content: '修改成功'
    })
    hideInput()
    hideList()
  }
  const onChangePhoto = async (e:React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0]
    if (!file) return
    const photoDate = new FormData()
    photoDate.append('photo', file)
    await dispatch(updateUserPhoto(photoDate))

    Toast.show({
      icon: 'success',
      content: '修改成功'
    })
    hideList()
  }
  const { user: userProfile } = useInitialState(getUserProfile, 'profile')
  console.log(userProfile, 777)

  // 退出登录
  const onLogout = () => {
    const handler = Dialog.show({
      title: '温馨提示',
      content: '亲，你确定退出吗？',
      closeOnAction: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            onClick: () => {
              handler.close()
            }
          },
          {
            key: 'confirm',
            text: '退出',
            onClick: () => {
              dispatch(logout())
              history.replace('/login')
              Toast.show({ content: '退出成功' })
            },
            style: {
              color: 'var(--adm-color-weak)'
            }
          }
        ]
      ]
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar onBack={() => history.go(-1)}
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={userProfile.photo}
                    alt=""
                  />
                </span>
              }
              arrow onClick={() => setShowList({ type: 'photo', visible: true })}
            >
              <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
              头像
            </Item>
            <Item arrow extra={userProfile.name} onClick={() => setShowInput({ visible: true, type: 'name' })}>
              昵称
            </Item>
            <Item
              arrow
              onClick={() => setShowInput({ visible: true, type: 'intro' }) }
              extra={
                <span className={classNames('intro', userProfile.intro && 'normal')}>
                  {userProfile.intro || '未填写'}
                </span>
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item onClick={() => setShowList({ type: 'gender', visible: true })} arrow extra={userProfile.gender ? '女' : '男'}>
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={onBirthdayShow}>
              生日
            </Item>

               <DatePicker
                visible={showBirthday}
                value={new Date(userProfile.birthday)}
                onCancel={onBirthdayHide}
                onConfirm={onUpdateBirthday}
                title="选择年月日"
                min={new Date(1900, 0, 1, 0, 0, 0)}
                max={new Date()}
              />
          </List>

          <DatePicker
            visible={false}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button onClick={onLogout} className="btn">退出登录</Button>
        </div>
      </div>
      {/* 编辑昵称和简介 */}
      <Popup visible={showInput.visible} position='right' destroyOnClose>
        <EditInput hideName={hideInput} type={showInput.type} onUpdate={onUpdate} />
      </Popup>
      {/* 编辑性别和头像 */}
      <Popup visible={showList.visible} destroyOnClose onMaskClick={hideList} position='bottom'>
         <EditList hideList={hideList} type={showList.type} onUpdate={onUpdate}/>
      </Popup>
    </div>
  )
}

export default ProfileEdit
